<?php

namespace app\admin\controller;

use think\db\exception\PDOException;
use think\Exception;
use Throwable;
use app\common\controller\Backend;

/**
 * 项目
 */
class ProjectFeeitem extends Backend
{
    /**
     * Project模型对象
     * @var object
     * @phpstan-var \app\common\model\Project
     */
    protected object $model;

    protected array $noNeedPermission = ['index', 'update', 'feeitemDetail', 'updateRemark', 'feeitemsDetail'];

    public function initialize(): void
    {
        parent::initialize();
        $this->model = new \app\admin\model\ProjectFeeitem();
    }

    public function index(): void
    {
        $list = $this->getProjectFeeitems();

        $this->success('', [
            'list'   => $list,
            'total'  => count($list)
        ]);
    }

    public function update(): void
    {
        $project_id = request()->post('project_id');
        $lists = request()->post('lists');
        $project_feeitems = $this->getProjectFeeitems();
        $hasFeeItemIds = array_column($project_feeitems, 'feeitem_id');
        $setIds = array_column($lists, 'feeitem_id');
        $deleteIds = [];
        $saveDatas = [];
        try {
            foreach ($lists as $v){
                // 没有设置过的 直接添加
                if(!in_array($v['feeitem_id'], $hasFeeItemIds)){
                    $saveDatas[] = $v;
                } else { // 已经设置过的 修改
                    $this->model->where([
                        'project_id'=> $v['project_id'],
                        'feeitem_id'=> $v['feeitem_id'],
                    ])->save([
                        'feeitem_name'=> $v['feeitem_name'],
                        'unit'=> $v['unit'],
                        'qty'=> $v['qty'],
                        'trems'=> $v['trems'],
                        'rate'=> $v['rate'],
                        'budget'=> $v['budget']
                    ]);
                }
            }
            foreach ($hasFeeItemIds as $v){
                if(!in_array($v, $setIds)) $deleteIds[] = $v;
            }
            if(count($deleteIds) > 0){
                $this->model->where([
                    ['project_id', '=', $project_id],
                    ['feeitem_id', 'in', $deleteIds],
                ])->delete();
            }
            $this->model->saveAll($saveDatas);
            $this->success('保存成功');
        } catch (PDOException|Exception $e) {
            $this->error('保存失败', ['msg' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine()]);
        }
    }

    public function updateRemark(): void
    {
        try {
            $data = $this->request->post();
            $this->model->saveAll($data);
        } catch (\PDOException $e){
            $this->error('保存失败', ['msg' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine()]);
        }
    }

    private function getProjectFeeitems(): Array {
        return $this->model->withSearch(['project_id'], request()->post())->order('feeitem_pid asc, id asc')->select()->toArray();
    }

    public function feeitemDetail(): void {
        $project_id = $this->request->post('project_id');
        $feeitem_id = $this->request->post('feeitem_id');

        $res = \app\admin\model\ProjectFeeitem::where([
            'project_id' => $project_id,
            'feeitem_id' => $feeitem_id
        ])->find();
        $this->success('', $res);
    }

    public function feeitemsDetail(): void {
        $project_id = $this->request->post('project_id');
        $feeitem_id = $this->request->post('feeitem_id');

        $res = \app\admin\model\ProjectFeeitem::where([
            'project_id' => $project_id,
            ['feeitem_id', 'in', $feeitem_id]
        ])->field('sum(budget) budget, sum(calculate) calculate,sum(paid) paid')->find();
        $this->success('', $res);
    }
}